/*
 * Copyright (c) 2022 Huawei Technologies Co.,Ltd.
 *
 * openGauss is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *          http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.Types;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Date;

/**
 * @owner: opentestcase033
 * @time:  2023/7/14
 **/

public class Opengauss_SharedStorage_MultiNodeWrite_Case0053 {
    static public String driver = "org.postgresql.Driver";
    static public String tb_name;
    static public String func_name;
    public static Properties getConfigFromFile(String filePath) {
        Properties props = new Properties();
        try {
            BufferedInputStream config = new BufferedInputStream(new FileInputStream(filePath));
            props.load(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return props;
    }

    public static String genURLFromPro(Properties props) {
        String hostname = props.getProperty("hostname");
        String[] hostnames = hostname.split(",");
        String port = props.getProperty("port");
        String[] ports = port.split(",");
        String dbname = props.getProperty("dbname");
        tb_name = props.getProperty("tbname");
        func_name = props.getProperty("funcname");
        return genURLFromHostsPortsDBname(hostnames, ports, dbname);
    }

    public static String genURLFromHostsPortsDBname(String[] hostnames, String[] ports, String dbname) {
        String sourceURL;
        if (hostnames.length == 1) {
            sourceURL = "jdbc:postgresql://" + hostnames[0] + ":" + ports[0] + "/" + dbname;
        } else {
            ArrayList<String> ip_port_pare = new ArrayList<>();
            if (ports.length == 1) {
                for (String ip : hostnames) {
                    ip_port_pare.add(ip + ":" + ports[0]);
                }
            } else {
                for (int i = 0; i < hostnames.length; i++) {
                    ip_port_pare.add(hostnames[i] + ":" + ports[i]);
                }
            }
            sourceURL = "jdbc:postgresql://" + String.join(",", ip_port_pare) + "/" + dbname;
        }
        return sourceURL;
    }

    public static Connection GetConnection(Properties props) {
        Connection connR;
        String sourceURL = genURLFromPro(props);
        System.out.println(sourceURL);
        try {
            Class.forName(driver).newInstance();
            connR = DriverManager.getConnection(sourceURL, props);
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
        return connR;
    }

    public static void CreateFunction(Connection conn) throws InterruptedException {
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            stmt.execute("create or replace function " + func_name + "(tb_name varchar) return varchar is "
                    + "begin "
                    + "execute immediate 'create table  '|| tb_name || '(id int, name varchar(20));';"
                    + "return tb_name;"
                    + "end;");
            stmt.execute("drop table if exists " + tb_name + " cascade;"
                    + "create table " + tb_name + "(id int, name varchar(20)) with(segment=on);");
            stmt.execute("create or replace function " + func_name + "_dml() returns void as $$"
                    + "begin "
                    + "execute immediate 'insert into " + tb_name + " values (generate_series(1,10), ''test'');';"
                    + "execute immediate 'update " + tb_name + " set name=''software'' where id = 3;';"
                    + "execute immediate 'delete from " + tb_name + " where id = 5;';"
                    + "end;"
                    + "$$ LANGUAGE plpgsql;");
                    Thread.sleep(1000);
                    stmt.close();
                } catch (SQLException e) {
                    if (stmt != null) {
                        try {
                            stmt.close();
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                    e.printStackTrace();
                }
    }

        public static void QueryFunction(Connection conn) {
            Statement stmt = null;
                try {
                    stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery("select t1.proname, t2.usename from pg_proc t1 inner join pg_user t2 "
                                                        + "on t2.usesysid=t1.proowner where proname like '" + func_name + "%';");
                        while (rs.next())
                                {
                                    System.out.println(rs.getString("proname") + " | " +  rs.getString("usename"));
                                }
                } catch (SQLException e) {
                        e.printStackTrace();
                }
        }

    public static void ExecCallableFunction(Connection conn) {
        CallableStatement cstmt_ddl = null;
        CallableStatement cstmt_dml = null;
        try {
            cstmt_ddl=conn.prepareCall("{call " + func_name + "(?)}");
            cstmt_ddl.registerOutParameter(1, Types.VARCHAR);
            cstmt_ddl.setString(1, tb_name + "_err");
            cstmt_ddl.execute();
            ResultSet res = cstmt_ddl.getResultSet();
            System.out.println("The CallableStatment " + func_name + " returns:" + res);
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (cstmt_ddl != null) cstmt_ddl.close();
                cstmt_dml=conn.prepareCall("{call " + func_name + "_dml()}");
                cstmt_dml.execute();
                cstmt_dml.close();
            } catch (SQLException e1) {
                    e1.printStackTrace();
            }
        }
    }

    public static void DropStatement(Connection conn) throws InterruptedException {
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            stmt.execute("drop table if exists " + tb_name + " cascade;");
            stmt.execute("drop function " + func_name + "_dml();");
            stmt.execute("drop function " + func_name + "();");
            Thread.sleep(100);
            stmt.close();
        } catch (SQLException e) {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Properties pros = new Properties();
        Properties pros_conf=null;
        String jdbc_config_file = null;
        for (int i = 0; i < args.length; i++) {
            switch (args[i]) {
                case "--config-file":
                    jdbc_config_file = args[i + 1];
                    pros_conf=getConfigFromFile(jdbc_config_file);
                    break;
                case "-F":
                    jdbc_config_file = args[i + 1];
                    pros_conf=getConfigFromFile(jdbc_config_file);
                    break;
                default:
                    break;
            }
        }
        //建立连接
        if (pros_conf!=null){
            //以参数为准，覆盖配置文件中的
            pros_conf.putAll(pros);
        }
        Connection conn = GetConnection(pros_conf);
        Statement stmt = null;
        CreateFunction(conn);
        QueryFunction(conn);
        ExecCallableFunction(conn);
        DropStatement(conn);
        try {
          conn.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
    }
}
